using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using System.Xml.Serialization;
using Microsoft.Win32;
using Samurai.Infrastructure;

namespace Samurai.Client.Commands
{
    public class ImportCommand : CommandBase
    {
        private readonly ObservableCollection<Movie> _movies;

        public ImportCommand(ObservableCollection<Movie> movies)
        {
            _movies = movies;
        }

        #region Implementation of ICommand

        protected override void InvokeExecute(object parameter)
        {
            var dlg = new OpenFileDialog();

            var response = dlg.ShowDialog();

            if (response.Value == true)
            {

                var fileName = dlg.FileName;

                List<Movie> importedMovies = null;

                if (LongOperationStarted != null)
                    LongOperationStarted();

                Application.Current.Dispatcher.Invoke(
                    new Action
                        (
                        () =>
                            {
                                importedMovies = Import(fileName, importedMovies);
                            }
                        )
                    );

                Load(importedMovies);

                if (LongOperationFinished != null)
                    LongOperationFinished();
            }
        }

        private void Load(List<Movie> importedMovies)
        {
            _movies.Clear();

            foreach (var movie in importedMovies)
            {
                _movies.Add(movie);
                System.Windows.Forms.Application.DoEvents();
            }
        }

        private static List<Movie> Import(string fileName, List<Movie> importedMovies)
        {
            var sr = File.OpenRead(fileName);

            var instance = new XmlSerializer(typeof(List<Movie>));

            importedMovies = (List<Movie>)instance.Deserialize(sr);

            sr.Close();
            return importedMovies;
        }

        #endregion
    }
}